package com.yisoo.ubag.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.yisoo.common.constant.RedisStringConstant;
import com.yisoo.common.to.EmailDataTo;
import com.yisoo.common.utils.R;
import com.yisoo.common.vo.LoginStatusVo;
import com.yisoo.ubag.product.feign.IotFeignService;
import com.yisoo.ubag.product.feign.ThirdPartyFeignService;
import com.yisoo.ubag.product.interceptor.LoginUserInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yisoo.common.utils.PageUtils;
import com.yisoo.common.utils.Query;

import com.yisoo.ubag.product.dao.ConsumerDao;
import com.yisoo.ubag.product.entity.ConsumerEntity;
import com.yisoo.ubag.product.service.ConsumerService;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("consumerService")
public class ConsumerServiceImpl extends ServiceImpl<ConsumerDao, ConsumerEntity> implements ConsumerService {
    private ThreadLocal<LoginStatusVo> loginStatusVoThreadLocal = new ThreadLocal<>();

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    ThirdPartyFeignService  thirdPartyFeignService;
    @Autowired
    ThreadPoolExecutor executor;
    @Autowired
    ConsumerService consumerService;
    @Autowired
    IotFeignService iotFeignService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ConsumerEntity> page = this.page(
                new Query<ConsumerEntity>().getPage(params),
                new QueryWrapper<ConsumerEntity>()
        );

        return new PageUtils(page);
    }

    //查询是否注册为商家
    @Override
    public R getRegCheckInfo(String cid) {
//        1. 检查id 是否存在
        ConsumerEntity entity = this.getById(cid);

        if(entity == null){
            return R.error(-1,"未注册");
        }
//        2. 如果存在就看状态
//        3、不存在就认为是未注册
        //存在 看 status ；分为两种 0 和 1
        //1 是完成认证
        //0 看缓存有没有验证码，有验证码就让填验证码 status为2，没验证码就返回0
        if (entity.getStatus().equals("0")){
            //判断是否有缓存
            String CODE = RedisStringConstant.CHECK_CODE+entity.getConsumerId();
//            System.out.println(CODE);
            if (stringRedisTemplate.hasKey(CODE)){
                entity.setStatus("2");
            }
        }
        return  R.ok().put("data",entity);
    }

    @Override
    public R Sendcode(ConsumerEntity consumer) {
        if (consumer.getConsumerId() == null && consumer.getEmail() == null){
            return R.error("邮箱异常");
        }
//        LoginStatusVo loginStatusVo = LoginUserInterceptor.loginUser.get();
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        String Code = UUID.randomUUID().toString().substring(0,5);
        System.out.println(Code);
        String key = RedisStringConstant.CHECK_CODE+consumer.getConsumerId();

        CompletableFuture<Void> Future = CompletableFuture.runAsync(() -> {
            //每一个线程都来共享之前的请求数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            stringRedisTemplate.opsForValue().set(key, Code,60*5, TimeUnit.SECONDS);
        }, executor);
        CompletableFuture<Void> Future2 = CompletableFuture.runAsync(() ->{
            //发送邮件
            EmailDataTo emailDataTo = new EmailDataTo(consumer.getEmail(), "Yisoo通知", "content", null);
            emailDataTo.setEmailParam("验证码校验","申请开通设备token",consumer.getUsername(),Code,"5分钟");
//            System.out.println(emailDataTo);
            thirdPartyFeignService.sendMail(emailDataTo);
        }, executor);
        try {
            CompletableFuture.allOf(Future,Future2).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } finally {
            return R.ok();
        }
    }

    @Override
    public R Checkcode(Long cid, String vcode) {
        String key = RedisStringConstant.CHECK_CODE+cid;
        String s = stringRedisTemplate.opsForValue().get(key);
        if (s != null && vcode!=null && vcode.equals(s)){
            ConsumerEntity entity = baseMapper.selectById(cid);
            entity.setStatus("1");
            baseMapper.updateById(entity);

            //校验成功之后，为用户创建一个产品
            String username = consumerService.getById(cid).getUsername();
            iotFeignService.Add(cid,username+String.valueOf(cid));


            return R.ok();
        }
        return R.error("验证码校验失败");
    }


}